<template>
  <div class="page-common-layout project-data-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-input
            placeholder="项目名称"
            style="width:350px!important"
            v-model="orgName"
          ></a-input>
          <a-select
            v-model="workArea"
            placeholder="请选择区位"
            :filter-option="filterOption"
            allowClear
            showSearch
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="(item, index) in workAreaSoucre"
              :key="index"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="project-body-container">
      <div class="operate" v-action:projectAddDialog>
        <a-dropdown>
          <a-menu slot="overlay">
            <a-menu-item
              v-for="item in groupButtons"
              :key="item.uuid"
              @click="handleAdd($event, item)"
            >
              <a-icon type="plus" />
              新建{{ item.dicItemName }}
            </a-menu-item>
          </a-menu>
          <a-button class="cu-btn-primary" icon="plus">
            新建
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
          :tree-config="{
            rowField: 'id',
            parentField: 'pid',
            hasChildField: 'hasChild',
            lazy: true,
            loadMethod: loadChildrenMethod,
            iconOpen: 'vxe-icon-square-minus',
            iconClose: 'vxe-icon-square-plus',
          }"
          :row-config="{
            isHover: true,
          }"
          @toggle-tree-expand="handleExpandedChanged"
          :row-class-name="rowClass"
        >
          <vxe-column field="orgSort" title="排序" width="80"> </vxe-column>
          <vxe-column
            field="orgName"
            title="名称"
            min-width="200"
            tree-node
            align="left"
          >
          </vxe-column>
          <vxe-column title="类型" width="100">
            <template #default="{ row }">
              {{ row.secType || row.orgTypeDesc }}
            </template>
          </vxe-column>
          <vxe-column field="orgNuitName" title="承包方"> </vxe-column>
          <vxe-column field="workArea" title="区位"> </vxe-column>
          <vxe-column width="60" title="编辑" align="left">
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button type="link" @click="handleEdit(row)">
                  编辑
                </a-button>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="createTime" title="创建时间"> </vxe-column>
          <vxe-column
            field="operate"
            width="160"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  type="link"
                  class="danger"
                  @click="handleDelClick(row)"
                >
                  删除
                </a-button>
                <a-button type="link" @click="previewUser(row)">
                  查看用户
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 项目新增编辑 -->
    <peojectForm
      ref="projectModal"
      :visible.sync="projectVisible"
      :model="projectMdl"
      :key="projectKey"
    ></peojectForm>

    <!-- 标段新增编辑 -->
    <blockForm
      ref="blockModal"
      :visible.sync="blockVisible"
      :model="blockMdl"
      :key="blockKey"
    ></blockForm>

    <user-view
      ref="userViewModal"
      v-if="userViewVisible"
      :visible="userViewVisible"
      :orgId="orgId"
      :orgName="orgName"
      @close="userViewVisible = false"
    >
    </user-view>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
import peojectForm from "./peojectEdit";
import blockForm from "./blockEdit";
import userView from "./userView";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import { flatTreeData, _getUUID } from "@/utils/util.js";
import { getTreeProject } from "@/services/user.js";
export default {
  components: {
    ScreenConditions,
    peojectForm,
    blockForm,
    userView,
  },
  data() {
    return {
      //项目名称
      orgName: "",
      //区位
      workArea: undefined,
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      groupButtons: [],
      //项目
      projectKey: _getUUID(),
      projectVisible: false,
      projectMdl: {},
      //标段
      blockKey: _getUUID(),
      blockVisible: false,
      blockMdl: {},
      //产看用户
      userViewVisible: false,
      orgId: "",
      orgName: "",
      workAreaSoucre: [],
    };
  },
  mounted() {
    this.getAddTypeList();
    this.getWorkAreaData();
    this.getTableData();
  },
  methods: {
    //查询全局项目集合
    getTreeProjectData() {
      return new Promise((resolve, reject) => {
        getTreeProject()
          .then((res) => {
            let source = res.data || [];
            this.$store.dispatch("setStoreState", {
              TENANT_DATA: source,
            });
            resolve();
          })
          .catch((_) => {
            this.$store.dispatch("setStoreState", {
              TENANT_DATA: [],
            });
            reject();
          });
      });
    },

    rowClass({ row }) {
      if (row.rowClass) {
        return "open";
      } else {
        return "";
      }
    },

    handleExpandedChanged({ expanded, row }) {
      let array = this.tableData.filter((v) => v.uuid == row.uuid);
      if (expanded) {
        setTimeout(() => {
          let flatData = flatTreeData(array, "children");
          flatData.forEach((v) => {
            this.$set(v, "rowClass", true);
          });
        }, 500);
      } else {
        setTimeout(() => {
          let flatData = flatTreeData(array, "children");
          flatData.forEach((v) => {
            this.$set(v, "rowClass", false);
          });
        }, 300);
      }
    },

    search() {
      this.pager.page = 1;
      this.getTableData();
    },
    reset() {
      this.workArea = undefined;
      this.orgName = "";
      this.getTableData();
    },
    // 新增
    handleAdd(key, item) {
      let { dicItemCode, dicItemName } = item;
      //项目
      if (dicItemCode == "org_type.04") {
        this.projectKey = Date.now();
        this.projectVisible = true;
        this.projectMdl = {
          text: "新建" + dicItemName,
        };
      }
      //标段
      else if (dicItemCode == "org_type.05") {
        this.blockKey = Date.now();
        this.blockVisible = true;
        this.blockMdl = {
          text: "新建" + dicItemName,
        };
      }
    },

    //编辑
    handleEdit(record) {
      this.$post("/mdata/organization/getDetailByUuid", {
        uuid: record.uuid,
      }).then((res) => {
        if (res.statusCode === 200) {
          if (record.orgType == "org_type.04") {
            this.projectMdl = {
              text: "编辑",
              ...res.data,
            };
            this.projectVisible = true;
          } else if (record.orgType == "org_type.05") {
            this.blockMdl = {
              text: "编辑",
              ...res.data,
            };
            this.blockVisible = true;
          }
        }
      });
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that
            .$post("/mdata/organization/delete", {
              uuid: row.uuid,
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTreeProjectData();
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      axios
        .post(
          `/mdata/organization/getTreeSysOrganizationByPage?pageNo=${page}&pageSize=${pageSize}`,
          {
            orgName: this.orgName,
            workArea: this.workArea ?? "",
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.tableData = data?.rows || [];
          this.pager.total = data?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    loadChildrenMethod({ row }) {
      let { id } = row;
      return new Promise((resolve) => {
        axios
          .post(
            `/mdata/organization/getTreeDataByPid?pid=${id}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.childData = res?.data ?? [];
            resolve(res?.data ?? []);
          });
      });
    },
    //查询新增类型
    getAddTypeList() {
      this.$post("/system/dicSet/getDicItemByCode", {
        code: "OrganizationsType",
      })
        .then((res) => {
          let { data } = res;
          this.groupButtons = data ?? [];
          let code = ["org_type.04", "org_type.05"];
          this.groupButtons = this.groupButtons.filter((v) =>
            code.includes(v.dicItemCode)
          );
        })
        .catch((_) => {
          this.groupButtons = [];
        })
        .finally((_) => {});
    },
    //查询区位
    getWorkAreaData() {
      this.$post("/system/dicSet/getDicItemByCode", {
        code: "workArea",
      })
        .then((res) => {
          let { data } = res;
          this.workAreaSoucre = data ?? [];
        })
        .catch((_) => {
          this.workAreaSoucre = [];
        })
        .finally((_) => {});
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    previewUser(record) {
      this.userViewVisible = true;
      this.orgId = record.id;
      this.orgName = "查看用户-【" + record.orgName + "】";
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.project-data-container {
  display: flex;
  flex-direction: column;
  .project-body-container {
    flex: 1;
    background-color: @base-bg-color;
    flex-shrink: 0;
    position: relative;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .operate {
      display: flex;
      margin-bottom: 10px;
    }
    .main {
      flex: 1;
      /deep/.open {
        background: #f5f7fa;
      }
      .more {
        margin-left: 16px;
      }
    }
    .pager-container {
      flex-shrink: 0;
      box-sizing: border-box;
    }
  }
}
</style>
